package com.shujia.wyh.weather;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;

/*
    求出2000年到2022年的2月份的最高温度
 */
class WeatherMapper extends Mapper<LongWritable, Text, Text, LongWritable> {
    @Override
    protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, LongWritable>.Context context) throws IOException, InterruptedException {
        //2012-06-23 11:45:11,-9
        String line = value.toString();
        String[] strings = line.split(",");
        String month = strings[0].split("-")[1];
        String temp = strings[1];

        if ("02".equals(month)) {
            context.write(new Text(month), new LongWritable(Long.parseLong(temp)));
        }
    }
}

class WeatherReducer extends Reducer<Text, LongWritable, Text, LongWritable> {
    @Override
    protected void reduce(Text key, Iterable<LongWritable> values, Reducer<Text, LongWritable, Text, LongWritable>.Context context) throws IOException, InterruptedException {
        long maxNum = 0;

        for (LongWritable value : values) {
            long temp = value.get();
            if (temp > maxNum) {
                maxNum = temp;
            }
        }

        context.write(key, new LongWritable(maxNum));
    }
}


public class WeatherDemo {
    public static void main(String[] args) throws Exception {
        //获取hadoop环境配置
        Configuration conf = new Configuration();
        //获取Job作业
        Job job = Job.getInstance(conf);

        //添加预聚合
        job.setCombinerClass(WeatherReducer.class);

        //设置job的主类
        job.setJarByClass(WeatherDemo.class);
        //设置job作业的名字
        job.setJobName("求出2000年到2022年的2月份的最高温度");

        //设置map类
        job.setMapperClass(WeatherMapper.class);
        //设置map的输出类型
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(LongWritable.class);

        //设置reduce类
        job.setReducerClass(WeatherReducer.class);
        //设置最终的输出类型
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(LongWritable.class);

        //设置数据的来源路径
        FileInputFormat.addInputPath(job, new Path(args[0]));
        //设置输出的路径
        FileOutputFormat.setOutputPath(job, new Path(args[1]));

        //提交作业到yarn上执行
        job.waitForCompletion(true);


    }
}
